import { useLocalStorage } from '@vueuse/core'
import { useUserStore } from '@/stores/user'

export interface Issue {
  id: number
  title: string
  teacherID: string
  teacherName: string
  status: boolean
  content: string
}

export function useIssueStore() {
  const issues = useLocalStorage<Issue[]>('issues', [], {
    deep: true,
    listenToStorageChanges: true
  })

  const userStore = useUserStore()

  const addIssue = ({ title, content }: Pick<Issue, 'title' | 'content'>) => {
    const id = issues.value.reduce((newId, { id }) => (newId > id ? newId : id + 1), 1)

    issues.value.push({
      title,
      content,
      id,
      teacherID: userStore.user.username,
      teacherName: userStore.user.name,
      status: false
    })
  }

  const removeIssue = (id: number) => {
    issues.value = issues.value.filter((issue) => issue.id !== id)
  }

  const updateIssue = (id: number, issue: Issue) => {
    const index = issues.value.findIndex((issue) => issue.id === id)
    if (index !== -1) {
      issues.value[index] = issue
    }
  }

  const searchIssueById = (id: number) => issues.value.find((issue) => issue.id === id)

  return {
    issues,

    addIssue,
    removeIssue,
    updateIssue,
    searchIssueById
  }
}
